#!/usr/bin/env python
#  -*- coding: utf-8 -*-

"""
    MCC 118 Functions Demonstrated:
        mcc118.a_in_scan_start
        mcc118.a_in_scan_read
        mcc118.a_in_scan_stop
        mcc118.a_in_scan_cleanup

    Purpose:
        Perform a continuous acquisition on 1 or more channels.

    Description:
        Continuously acquires blocks of analog input data for a
        user-specified group of channels until the acquisition is
        stopped by the user.  The last sample of data for each channel
        is displayed for each block of data received from the device.
        MCC118共8个通道，可以监测两个三相变压器的6路市电，分别为变压器1的A、B、C相和变压器2的A、B、C相
"""
from __future__ import print_function
import os
import threading
import numpy as np
import datetime
import sys
import time
import signal

from ad7606 import ad7606, HatError

# ===================================================================================
parameter=sys.argv
READ_ALL_AVAILABLE = -1
CURSOR_BACK_2 = '\x1b[2D'
ERASE_TO_END_OF_LINE = '\x1b[0K'
# ===================================================================================
path="/media/pi/Seagate/data"
path="/home/pi/Seagate/data"
os.chdir(path)
# =======Channel set==================================================================
# Store the channels in a list and convert the list to a channel mask that
# can be passed as a parameter to the MCC 118 functions.
channels = [3, 4, 5]  #外壳丝印第一、二路与变压板1，2路反了，此处调整过来
channel_mask = channels
num_channels = len(channels)
samples_per_channel = 0
options = None  # OptionFlags.CONTINUOUS
scan_rate = 3600.0                     #采样速率 最大值为100k/信道数
read_request_size = 3600               #每通道此次采样的点数
c_time = 10                             #连续采样的次数
timeout = 10.0
running = True

# ======传入参数======================================================================
if len(parameter[1]) > 7 and 3600 <= float(parameter[1][4:]) <= 7200:
    scan_rate=int(parameter[1][4:])
    print(scan_rate)

if len(parameter[2]) > 7 and 3600 <= float(parameter[2][4:]) <= 20000:
    read_request_size=int(parameter[2][4:])
    print(read_request_size)

print(scan_rate)
print(read_request_size)
#================================================================================================

arraydata=[[0 for i in range(read_request_size*num_channels)] for h in range(c_time)]
#====Analyse and writefile and Alarm=======================================================
def analyse(array,fnat):
    print("analyse   file    ", datetime.datetime.now())
    file1 = "1-"+fnat
    
    a=np.array(array)
    b = np.empty([3, c_time*read_request_size], dtype=float)  # 变压器1定义一个数组

    #板子的数据记录格式是：CH0、CH1、CH2、CH0、CH1、CH2、CH0、CH1、CH2、CH0、CH1、CH2、CH0、CH1、CH2
    #通过下面拆分成3个CH每个CH一个list以便进行分CH判断
    b[0] = np.concatenate((a[0, 0::3], a[1, 0::3], a[2, 0::3], a[3, 0::3], a[4, 0::3], a[5, 0::3], a[6, 0::3],a[7, 0::3], a[8, 0::3], a[9, 0::3]))  #提取变压器1,A相数据
    b[1] = np.concatenate((a[0, 1::3], a[1, 1::3], a[2, 1::3], a[3, 1::3], a[4, 1::3], a[5, 1::3], a[6, 1::3],a[7, 1::3], a[8, 1::3], a[9, 1::3]))  #提取变压器1,B相数据
    b[2] = np.concatenate((a[0, 2::3], a[1, 2::3], a[2, 2::3], a[3, 2::3], a[4, 2::3], a[5, 2::3], a[6, 2::3],a[7, 2::3], a[8, 2::3], a[9, 2::3]))  #提取变压器1,C相数据
    
    np.savetxt(file1, b.T, fmt="%1.2f", delimiter=" ")

    print("\033[0;32m","analyse finish    ", datetime.datetime.now(),"\033[0m")    #font color
# ============================================================================================

def handler(signum, frame):
    global running
    signame = signal.Signals(signum).name
    print(f'Signal handler called with signal {signame} ({signum})')
    print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')
    print('Stopping')
    running = False

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)


def main():
    """
    This function is executed automatically when the module is run directly.
    """
# ============================================================================================
    try:
        # Select an MCC 118 HAT device to use.
        hat = ad7606()
        '''
        print('\nSelected MCC 118 HAT device at address', address)
        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)
        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('         mcc118.a_in_scan_stop')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))
# ============================================================================================
        try:
            input('\nPress ENTER to continue ...')
        except (NameError, SyntaxError):
            pass
        '''
        # Configure and start the scan.
        # Since the continuous option is being used, the samples_per_channel
        # parameter is ignored if the value is less than the default internal
        # buffer size (10000 * num_channels in this case). If a larger internal
        # buffer size is desired, set the value of this parameter accordingly. 
        print('Starting scan ... Press Ctrl-C to stop\n')
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,options)
        hat.a_in_scan_read(read_request_size * c_time, timeout * c_time)
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate, options)
        # ============================================================================================
        while running:
            now_time = datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S.%f')
            fna = str(now_time) + ".txt"
            #连续采样10次
            timeout_happen = False
            print("sampled start: ", datetime.datetime.now())
            for i in range(c_time):
                read_result = hat.a_in_scan_read(read_request_size, timeout)  # read channel Data
                arraydata[i]=read_result.data

                if read_result.hardware_overrun:
                    print('\n\nHardware overrun\n')
                    break
                elif read_result.buffer_overrun:
                    print('\n\nBuffer overrun\n')
                    break
                elif read_result.timeout:
                    print('\n\nSample timeout, maybe SPI bus is too busy\n')
                    timeout_happen = True
                    break

                hat.a_in_scan_stop()
                hat.a_in_scan_cleanup()
                hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,options)
                if not running:
                    break

            if timeout_happen:
                continue  # don't analyse, try sample again, will succeed when SD card read/write done

            print("sampled done: ", datetime.datetime.now())
            if not running:
                break

            #调用分析进程
            arraydatat = arraydata
            t2 = threading.Thread(target=analyse, args=(arraydatat, fna, ))
            t2.start()  # switch to another CPU core, avoid burning single core forever
            t2.join()  # wait until the analysis done, avoid SD card read/write interferes AD7606 sampling

        hat.a_in_scan_stop()
        hat.a_in_scan_cleanup()

    except (HatError, ValueError) as err:
        print('\n', err)

# ==================================================================================================================
if __name__ == '__main__':
    main()

